<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-row class="search-input">
          <el-form-item prop="configId" label="轮播图类型：">
           <el-select v-model="filters.configId" placeholder="轮播图类型">
                <el-option
                v-for="item in configIdList"
                :key="item.config_id"
                :label="item.label"
                :value="item.config_id">
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="status" label="可用状态：">
             <el-select v-model="filters.status" placeholder="可用状态">
                  <el-option
                  v-for="item in statusOption"
                  :key="item.status"
                  :label="item.label"
                  :value="item.status">
                  </el-option>
              </el-select>
          </el-form-item>
        </el-row>
        <el-row class="search-button">
          <el-form-item>
            <kt-button
              icon="fa fa-search"
              :label="$t('action.search')"
              type="primary"
              @click="findPage(null)"
            />
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-refresh" :label="$t('action.reset')" type="primary" @click="resetForm('filters')" />
          </el-form-item>
          <el-form-item>
            <kt-button
              icon="fa fa-plus"
              :label="$t('action.add')"
              type="primary"
              @click="handleAdd"
            />
          </el-form-item>
          <el-form-item>
            <kt-button label="启用/停用" type="primary" @click="editStatus" />
          </el-form-item>

        </el-row>
         <el-form-item class="t_r w100">
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
             <!--表格显示列界面-->
      <table-column-filter-dialog
        ref="tableColumnFilterDialog"
        :columns="columns"
        @handleFilterColumns="handleFilterColumns"
      ></table-column-filter-dialog>
      </el-form>
    </div>
    <!--表格内容栏-->
    <cy-table
      :height="350"
      :max-height = "400"
      :data="pageResult"
      :columns="filterColumns"
      :showEditOperation="false"
      @findPage="findPage"
      @handleEdit="handleEdit"
      @handleDelete="handleDelete"
      @selectionChange="selectionChange"
      ref="CyTable"
    ></cy-table>
    <!--新增编辑界面-->
    <el-dialog
      :title="operation?'新增':'编辑'"
      width="40%"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="dataForm"
        label-width="120px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size"
      >
        <el-form-item label="ID：" prop="id" v-if="false">
          <el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="轮播图：" prop="CarouselFigurePic">
          <el-upload align="left"
            class="avatar-uploader"
            :action="excelUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess_arousel_figure_img"
            :before-upload="beforeAvatarUpload">
            <img v-if="dataForm.CarouselFigurePic" :src="dataForm.CarouselFigurePic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="configId" label="轮播图类型：">
          <el-select v-model="dataForm.configId" placeholder="轮播图类型">
            <el-option
              v-for="item in configIdList"
              :key="item.config_id"
              :label="item.label"
              :value="item.config_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="sort" label="排序：">
          <el-input-number
            v-model="dataForm.sort"
            auto-complete="off"
            :min="1"
            style="width: 50%"
          ></el-input-number>
        </el-form-item>
        <el-form-item prop="status" label="可用状态：">
          <el-select v-model="dataForm.status" placeholder="可用状态">
            <el-option
              v-for="item in statusOption"
              :key="item.status"
              :label="item.label"
              :value="item.status">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="editDialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitForm"
          :loading="editLoading"
        >{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CyTable from "@/views/Core/JicTable";
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
export default {
  components: {
    CyTable,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    return {
      size: "small",
      filters: {

      },
      excelUpload: this.utils.imgUploadUrl,
      // excelUpload: this.utils.getHost() +"/cmn/imgUpload?token=" +localStorage.getItem("token"),
      configIdList: [{
        config_id: '',
        label: '请选择'
      }, {
        config_id: '30',
        label: 'PC轮播图'
      }, {
        config_id: '31',
        label: 'H5轮播图'
      }],
      statusOption: [{
        status: '',
        label: '请选择'
      }, {
        status: 'N',
        label: '可用'
      }, {
        status: 'Y',
        label: '不可用'
      }],
      columns: [
        { prop: "id", label: "编号", minWidth: 50 },
        { prop: "pic", label: "图片", minWidth: 100,formatter: this.showPicType},
        { prop: "sort", label: "排序", minWidth: 100 },
        { prop: "configVal", label: "类型", minWidth: 80 },
        { prop: "status", label: "是否可用", minWidth: 120 ,formatter: this.showStatusType},
        { prop: "createTime", label: "创建时间", minWidth: 120 },
        { prop: "creatorName", label: "创建人", minWidth: 100 },
        { prop: "updateTime", label: "修改时间", minWidth: 100 },
        { prop: "updaterName", label: "修改人", minWidth: 100 }
	  ],
	  filterColumns:[],
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: {},


      operation: false, // true:新增, false:编辑
      editDialogVisible: false, // 新增编辑界面是否显示
      editLoading: false,
      dataFormRules: {
        sort: [
          { required: true, message: "请输入排序", trigger: "blur" },
          { required: true, message: "请输入排序",trigger: "change"}
        ],
        CarouselFigurePic: [{ required: true, message: "请上传轮播图", trigger: "blur" }],
        configId: [{ required: true, message: "请选择类型", trigger: "blur" }],
        status: [{ required: true, message: "请输入选择是否可用", trigger: "blur" }]
      },
      // 新增编辑界面数据
      dataForm: {
        id: "",
        CarouselFigurePic: "",
        sort: "",
        jump_link: "",
        configId: "",
        status: ""
      },
      //选中ID Array
      idArray:[]
    };
  },
  methods: {
    // 获取分页数据
    findPage: function(data) {
      let this_ = this;
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = this.pageRequest.pageNum;
      this_.filters.limit = this.pageRequest.pageSize;
      this.utils.request.querySysCarouselFigureList(this_.filters, function (res) {
        if (res.data.rows == null) {
          res.data.rows = [];
        }
        this_.$refs.CyTable.findPage({content:res.data.rows,total:res.data.total});
      });
    },
    //列表图片处理
    showPicType(row, column, cellValue, index) {
      if (row.pic != '' && row.pic != null) {
        return '<img src="'+row.pic+'" style="width: 150px;max-height	: 100px;"></img>';
      }
    },
    //列表状态处理
    showStatusType(row, column, cellValue, index) {
        if (row.status=='N') {
          return '可用';
        }else if(row.status=='Y') {
          return '不可用';
        }
    },
    //数据勾选
    selectionChange(data){
      console.log(data);
      this.idArray = data.selections;
    },
    // 批量删除
    handleDelete: function(data) {
      if (data != null && data.params != null && data.params.length > 0) {
        let ids = data.params.map(item => item.id).toString();
        console.log(ids);
        var params = {};
        params.ids = ids;
        var this_ = this;
        this.utils.request.deleteSysCarouselFigureInfo(params, function(res) {
          if (res.code == "0000") {
            this_.$message({ message: "操作成功", type: "success" });
            this_.findPage(null);
          } else {
            this_.$message({ message: "操作失败, " + res.msg, type: "error" });
          }
        });
      }
    },
    handleAvatarSuccess_arousel_figure_img(res, file) {
        this.dataForm.CarouselFigurePic = res.data.imgUrl
    },
    beforeAvatarUpload(file) {
      var isJPG =false;
      if(file.type === 'image/jpeg' || file.type === 'image/png'){
        isJPG = true;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message({
              message: '上传头像图片只能是 JPG 或 PNG 格式!',
              type: 'error',
              center:true,
              offset:250,
              duration:1000
        });
      }
      if (!isLt2M) {
         this.$message({
              message: '上传头像图片大小不能超过 2MB!',
              type: 'error',
              center:true,
              offset:250,
              duration:1000
        });
      }
      return isJPG && isLt2M;
    },
    // 显示新增界面
    handleAdd: function() {
      this.editDialogVisible = true;
      this.operation = true;
      this.resetForm("dataForm");
    },
    // 显示编辑界面
    handleEdit: function(params) {
      this.editDialogVisible = true;
      this.operation = false;
      this.$nextTick(function() {
        this.dataForm = Object.assign({}, params.row);
      });
    },
    //启用停用
    editStatus:function(){
      if(this.idArray.length<1){
        this.$message({
            message: '请选择需要操作的数据',
            type: 'error',
            center:true,
            offset:250,
            duration:1000
        });
        return false;
      }
      if(this.idArray.length>1){
        this.$message({
            message: '请选择单条数据',
            type: 'error',
            center:true,
            offset:250,
            duration:1000
        });
        return false;
      }
      let params = {'t':'carouselFigure'};
      params.id = this.idArray[0].id;
      if(this.idArray[0].status=='Y'){
        params.status = 'N';
      }else if(this.idArray[0].status=='N'){
        params.status = 'Y';
      }
      var this_ = this;
      this.utils.request.editSysCarouselFigureInfo(params, function(res) {
        this_.$message({message: '操作成功',type: 'success',center:true,offset:250,duration:1000});
        this_.findPage(null);
      });
    },
    // 编辑
    submitForm: function() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            let params = Object.assign({}, this.dataForm);

            params.t = "carouselFigure";
            var this_ = this;
            params.pic = this_.dataForm.CarouselFigurePic;
            this.utils.request.editSysCarouselFigureInfo(params, function(res) {
              if (res.code == "0000") {
                this_.$message({ message: "操作成功", type: "success" });

                this_.$refs["dataForm"].resetFields();

                this_.editDialogVisible = false;

                this_.findPage(null);
              } else {
                this_.$message({
                  message: "操作失败, " + res.msg,
                  type: "error"
                });
              }
            });
          });
        }
      });
    },

    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },

    resetForm(formName) {
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
        this.findPage(null);
      }
    },

    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      var temp = [];

      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
    //列表下载
    downloadExcel() {
      this.$confirm("确定下载列表文件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let filename = "轮播图管理下载";
          this.$refs.CyTable.exportData(
            this.filters,
            this.filterColumns,
            filename
          );
        })
        .catch(() => {});
    }

  },
  mounted() {
    this.initColumns();

  }
};
</script>

<style lang='scss' scoped>
.el-icon-plus {
  border: 1px dashed #d9d9d9;
  border-radius:6px;
  cursor:pointer;
  position:relative;
  overflow:hidden;
}
.el-icon-plus .el-upload:hover {
  border-color: #2F4554;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px!important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
